package com.mvp.networking;

import com.google.gson.JsonSyntaxException;
import com.mvp.R;
import com.mvp.base.BaseApplication;
import com.mvp.helper.AbsCrashHelper;
import com.mvp.utils.ResString;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.NetworkUtil;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;
import timber.log.Timber;

/**
 * api错误处理逻辑类，不同的数据源需要共用这个类，如果只有一种数据源可以直接在consumer后面处理；
 * Created by rui on 2018/7/31.
 */
public class ApiErrorHelper {

    public static void handleCommonError(Throwable throwable) {
        try {
            Timber.e("--->>>>>>>>---throwable:" + throwable.getMessage());
            if (throwable instanceof CustomThrowable) {
                if (((CustomThrowable) throwable).isToast()) {
                    ToastUtil.showToast(throwable.getMessage());
                }
            } else if (throwable instanceof IllegalStateException) {
            } else if (throwable instanceof ConnectException) {
                ToastUtil.showToast(ResString.get(R.string.net_error_nonetwork));
            } else if (throwable instanceof SocketTimeoutException) {
                ToastUtil.showToast(ResString.get(R.string.net_error_timeout));
            } else if (throwable instanceof HttpException) {
                int code = ((HttpException) throwable).code();
                String s = ResString.get(R.string.net_error_unavailableagain);
                ToastUtil.showToast(String.format(s, code));
            } else if (throwable instanceof UnknownHostException) {
                if (!NetworkUtil.isNetworkAvailable(BaseApplication.sContext)) {
                    ToastUtil.showToast(ResString.get(R.string.net_error_unavailable));
                } else {
                    ToastUtil.showToast(ResString.get(R.string.net_error_unknownservice));
                }
            } else if (throwable instanceof JsonSyntaxException) {
//            ToastUtil.showToast(throwable.getMessage());
            } else {
                ToastUtil.showToast(throwable.getMessage());
            }
        } catch (Exception e) {
            AbsCrashHelper.postCatchedException(e);
        }
    }


}
